<script setup lang="ts">
defineOptions({
  name: "ALL_ENERGY_ENERGYREPORT_RISK_OPP_ADD"
});

import { ref, reactive, computed, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { PxMessage } from "px-ui";
import type { FormInstance, FormRules } from "px-ui";
import { ArrowLeft } from "@px-ui/icons-vue";
import ReTeleport from "@/components/ReTeleport";
import { checkRiskOpportunityDetail, addEditRiskOpportunity } from "@/api/energy/overView";
import { queryChildByTypeCodeAndItemValue } from "@/api/solidity";
import { useThrottleFn } from "@vueuse/core";
import { throttleDelay as delay } from "@/utils/constant";

interface RuleForm {
  opportunity: string;
  kind: string;
  manageLink: string;
  area: string;
  process: string;
  device: string;
  impact: number;
  cost: number;
  ease: number;
  control: string;
  conservation: string;
  department: string;
}

const route = useRoute();
const router = useRouter();

const isShowReTeleport = computed(() => !route.path.includes("check"));
const score = computed(() => Number(ruleForm.value.impact) * Number(ruleForm.value.cost) * Number(ruleForm.value.ease) ?? "");
const priority = computed(() => {
  if (Number(score.value) >= 50) {
    return "high";
  } else if (Number(score.value) >= 20) {
    return "middle";
  } else if (Number(score.value) >= 0) {
    return "low";
  } else {
    return "";
  }
});

const loading = ref<boolean>(false);
const ruleFormRef = ref<InstanceType<typeof FormInstance>>();
const ruleForm = ref<RuleForm>({
  opportunity: "",
  kind: "",
  manageLink: "",
  area: "",
  process: "",
  device: "",
  impact: null,
  cost: null,
  ease: null,
  control: "",
  conservation: "",
  department: ""
});

const rules = reactive<InstanceType<typeof FormRules>>({
  opportunity: [{ required: true, message: "请输入节能机会", trigger: ["blur", "change"] }],
  kind: [{ required: true, message: "请选择能源种类", trigger: ["blur", "change"] }],
  manageLink: [{ required: true, message: "请选择管理环节", trigger: ["blur", "change"] }],
  area: [{ required: true, message: "请选择区域", trigger: ["blur", "change"] }],
  process: [{ required: true, message: "请选择工序/系统", trigger: ["blur", "change"] }],
  device: [{ required: true, message: "请选择设备/管理", trigger: ["blur", "change"] }],
  impact: [{ required: true, message: "请输入Impact", trigger: ["blur", "change"] }],
  cost: [{ required: true, message: "请输入Cost", trigger: ["blur", "change"] }],
  ease: [{ required: true, message: "请输入Ease", trigger: ["blur", "change"] }],
  control: [{ required: true, message: "请输入控制措施", trigger: ["blur", "change"] }],
  conservation: [{ required: false, message: "请输入预计节能", trigger: ["blur", "change"] }],
  department: [{ required: false, message: "请输入实施部门	", trigger: ["blur", "change"] }]
});

const kindOptions = ref<Array<{ value: string; label: string }>>([]);
const manageLinkOptions = ref<Array<{ value: string; label: string }>>([]);
const priorityOptions = ref<Array<{ value: string; label: string }>>([
  {
    value: "high",
    label: "高"
  },
  {
    value: "middle",
    label: "中"
  },
  {
    value: "low",
    label: "低"
  }
]);
const areaOptions = ref<Array<{ value: string; label: string }>>([]);
const processOptions = ref<Array<{ value: string; label: string }>>([]);
const deviceOptions = ref<Array<{ value: string; label: string }>>([]);

const channelInputLimit = (e: any) => {
  const key = e.key;
  const notAllowList = ["e", "E", "+", "-", "."];
  if (notAllowList.includes(key)) {
    e.returnValue = false;
    return false;
  }
  return true;
};
let value = "";
const handleCompositionStart = (e: any) => {
  value = e.target.value;
};
const handleCompositionEnd = (e: any, prop: string) => {
  e.target.value = value;
  ruleForm.value[prop] = value;
};

const cancelHandler = () => {
  const path = "/common/energy/energyReport/risk_opp";
  router.push({ path });
};

const submitHandler = useThrottleFn(async () => {
  if (!ruleFormRef.value) return;
  await ruleFormRef.value.validate(async valid => {
    if (valid) {
      const {
        query: { id = null }
      } = route;
      const params = { ...ruleForm.value, id };
      await addEditRiskOpportunity(params);
      const message = `${id ? "编辑" : "新增"}成功！`;
      PxMessage.success(message);
      cancelHandler();
    }
  });
}, delay);

const initOptions = async () => {
  // 能源种类
  queryChildByTypeCodeAndItemValue({ typeCode: "ENTS", value: "OPPORTUNITY_ENERGY_KIND" }).then(res => {
    kindOptions.value = res.map(item => ({ label: item.itemName, value: item.itemValue }));
  });
  // 管理环节
  queryChildByTypeCodeAndItemValue({ typeCode: "ENTS", value: "OPPORTUNITY_MANAGE_LINK" }).then(res => {
    manageLinkOptions.value = res.map(item => ({ label: item.itemName, value: item.itemValue }));
  });
  // 区域
  queryChildByTypeCodeAndItemValue({ typeCode: "ENTS", value: "OPPORTUNITY_AREA" }).then(res => {
    areaOptions.value = res.map(item => ({ label: item.itemName, value: item.itemValue }));
  });
  // 工序/系统
  queryChildByTypeCodeAndItemValue({ typeCode: "ENTS", value: "OPPORTUNITY_PROCESS" }).then(res => {
    processOptions.value = res.map(item => ({ label: item.itemName, value: item.itemValue }));
  });
  // 设备/管理
  queryChildByTypeCodeAndItemValue({ typeCode: "ENTS", value: "OPPORTUNITY_DEVICE" }).then(res => {
    deviceOptions.value = res.map(item => ({ label: item.itemName, value: item.itemValue }));
  });
};

const initData = async () => {
  const {
    query: { id = null }
  } = route;
  if (id) {
    const res = await checkRiskOpportunityDetail({ id });
    ruleForm.value.opportunity = res?.opportunity;
    ruleForm.value.kind = res?.kind;
    ruleForm.value.manageLink = res?.manageLink;
    ruleForm.value.area = res?.area;
    ruleForm.value.process = res?.process;
    ruleForm.value.device = res?.device;
    ruleForm.value.impact = res?.impact;
    ruleForm.value.cost = res?.cost;
    ruleForm.value.ease = res?.ease;
    ruleForm.value.control = res?.control;
    ruleForm.value.conservation = res?.conservation;
    ruleForm.value.department = res?.department;
  }
};

onMounted(async () => {
  await initOptions();
  await initData();
});
</script>

<template>
  <div v-loading="loading" class="risk-opp-add">
    <div class="add-btn">
      <px-button type="primary" :icon="ArrowLeft" @click="cancelHandler">返回</px-button>
    </div>
    <div class="add-content">
      <px-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="100px" class="rule-form" status-icon>
        <px-row :gutter="24">
          <px-col :span="24">
            <px-form-item label="节能机会" prop="opportunity">
              <px-input
                v-model.trim="ruleForm.opportunity"
                :disabled="!isShowReTeleport"
                :rows="2"
                type="textarea"
                maxlength="100"
                show-word-limit
                clearable
                placeholder="请输入节能机会"
              />
            </px-form-item>
          </px-col>

          <px-col :span="8">
            <px-form-item label="能源种类" prop="kind">
              <px-select v-model="ruleForm.kind" :disabled="!isShowReTeleport" clearable filterable reserve-keyword placeholder="请选择能源种类">
                <px-option v-for="item in kindOptions" :key="item.value" :label="item.label" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>

          <px-col :span="8">
            <px-form-item label="管理环节" prop="manageLink">
              <px-select
                v-model="ruleForm.manageLink"
                :disabled="!isShowReTeleport"
                clearable
                filterable
                reserve-keyword
                placeholder="请选择管理环节"
              >
                <px-option v-for="item in manageLinkOptions" :key="item.value" :label="item.label" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>

          <px-col :span="8">
            <px-form-item label="优先级" prop="">
              <px-select v-model="priority" disabled filterable reserve-keyword placeholder="请选择优先级">
                <px-option v-for="item in priorityOptions" :key="item.value" :label="item.label" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>

          <px-col :span="8">
            <px-form-item label="区域" prop="area">
              <px-select v-model="ruleForm.area" :disabled="!isShowReTeleport" clearable filterable reserve-keyword placeholder="请选择区域">
                <px-option v-for="item in areaOptions" :key="item.value" :label="item.label" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>

          <px-col :span="8">
            <px-form-item label="工序/系统" prop="process">
              <px-select v-model="ruleForm.process" :disabled="!isShowReTeleport" clearable filterable reserve-keyword placeholder="请选择工序/系统">
                <px-option v-for="item in processOptions" :key="item.value" :label="item.label" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>

          <px-col :span="8">
            <px-form-item label="设备/管理" prop="device">
              <px-select v-model="ruleForm.device" :disabled="!isShowReTeleport" clearable filterable reserve-keyword placeholder="请选择设备/管理">
                <px-option v-for="item in deviceOptions" :key="item.value" :label="item.label" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>

          <px-col :span="24">
            <div class="score">综合可行性得分：{{ score }}</div>
          </px-col>

          <px-col :span="8">
            <px-form-item label="Impact" prop="impact">
              <px-input-number
                v-model.trim.number="ruleForm.impact"
                :controls="false"
                :disabled="!isShowReTeleport"
                clearable
                :min="1"
                :max="5"
                :step="1"
                step-strictly
                placeholder="请输入Impact"
                @keydown="channelInputLimit"
                @compositionstart="handleCompositionStart($event)"
                @compositionend="handleCompositionEnd($event, 'impact')"
              />
            </px-form-item>
          </px-col>

          <px-col :span="8">
            <px-form-item label="Cost" prop="cost">
              <px-input-number
                v-model.trim.number="ruleForm.cost"
                :controls="false"
                :disabled="!isShowReTeleport"
                clearable
                :min="1"
                :max="5"
                :step="1"
                step-strictly
                placeholder="请输入Cost"
                @keydown="channelInputLimit"
                @compositionstart="handleCompositionStart($event)"
                @compositionend="handleCompositionEnd($event, 'cost')"
              />
            </px-form-item>
          </px-col>

          <px-col :span="8">
            <px-form-item label="Ease" prop="ease">
              <px-input-number
                v-model.trim.number="ruleForm.ease"
                :controls="false"
                :disabled="!isShowReTeleport"
                clearable
                :min="1"
                :max="5"
                :step="1"
                step-strictly
                placeholder="请输入Ease"
                @keydown="channelInputLimit"
                @compositionstart="handleCompositionStart($event)"
                @compositionend="handleCompositionEnd($event, 'ease')"
              />
            </px-form-item>
          </px-col>

          <px-col :span="24">
            <px-form-item label="控制措施" prop="control">
              <px-input
                v-model.trim="ruleForm.control"
                :disabled="!isShowReTeleport"
                :rows="2"
                type="textarea"
                maxlength="200"
                show-word-limit
                clearable
                placeholder="请输入控制措施"
              />
            </px-form-item>
          </px-col>

          <px-col :span="24">
            <px-form-item label="预计节能" prop="conservation">
              <px-input
                v-model.trim="ruleForm.conservation"
                :disabled="!isShowReTeleport"
                :rows="2"
                type="textarea"
                maxlength="200"
                show-word-limit
                clearable
                placeholder="请输入预计节能"
              />
            </px-form-item>
          </px-col>

          <px-col :span="24">
            <px-form-item label="实施部门	" prop="department">
              <px-input
                v-model.trim="ruleForm.department"
                :disabled="!isShowReTeleport"
                :rows="1"
                type="textarea"
                maxlength="100"
                show-word-limit
                clearable
                placeholder="请输入实施部门	"
              />
            </px-form-item>
          </px-col>
        </px-row>
      </px-form>
    </div>
    <ReTeleport v-if="isShowReTeleport" submitText="提交" @cancel="cancelHandler" @submit="submitHandler" />
  </div>
</template>

<style lang="scss" scoped>
.risk-opp-add {
  box-sizing: border-box;
  padding: 16px;
  background-color: #fff;

  .add-content {
    padding-top: 16px;

    .rule-form {
      box-sizing: border-box;
      padding-bottom: 0;

      .px-form-item {
        .px-input,
        .px-input-number,
        .px-select,
        .px-date-picker,
        .px-time-picker,
        .px-tree-select {
          width: 100%;
        }

        // :deep(.px-date-editor) {
        //   width: 100%;
        // }
      }
    }

    .score {
      margin-bottom: 16px;
      font-size: 15px;
      font-weight: 700;
      color: #333;
    }
  }
}
</style>
